package net.hn.hnms.biz.emgcy.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import net.hn.hnms.sys.common.core.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author admin
 * @since 1.0
 */
public class ExcelUtils {

    /**
     * 获取导入的校验信息
     *
     * @param file file
     * @return String
     */
    public static String getInvalidImportMessage(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            return "请上传文件!";
        }
        String suffix = ".xls";
        String suffix1 = ".xlsx";
        if ((!StringUtils.endsWithIgnoreCase(filename, suffix) && !StringUtils.endsWithIgnoreCase(filename, suffix1))) {
            return "导入文件不是excel文件类型!";
        }
        return null;
    }


    /**
     * 导出模板
     *
     * @param response   response
     * @param name       name
     * @param excelClass excelClass
     * @param list       list
     * @throws IOException IOException
     */
    public static void exportExcel(HttpServletResponse response, String name, Class<?> excelClass, List<?> list)
            throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String fileName = URLEncoder.encode(name, StandardCharsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), excelClass).sheet(name).doWrite(list);
    }

    /**
     * 导入文件
     *
     * @param file           file
     * @param excelClass     file
     * @param importListener importListener
     */
    public static void importExcel(MultipartFile file, Class<?> excelClass, AnalysisEventListener<?> importListener) {
        String invalidMessage = getInvalidImportMessage(file);
        if (invalidMessage != null) {
            throw new ServiceException(invalidMessage);
        }
        InputStream inputStream;
        try {
            inputStream = new BufferedInputStream(file.getInputStream());
            ExcelReaderBuilder builder = EasyExcel.read(inputStream, excelClass, importListener);
            builder.doReadAll();
        } catch (ServiceException populationException) {
            throw new ServiceException(populationException.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("数据格式错误");
        }
    }
}
